package com.yupi.shortchain.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class RateLimitServiceImpl {

    @Resource
    private RedissonClient redissonClient;


    // Redisson 实现 令牌桶算法 限流
    public RRateLimiter TokenLimiter(String key, long rate, long interval, RateIntervalUnit unit){
        RRateLimiter limiter = redissonClient.getRateLimiter(key);
        //限流器类型 限流器速率（规定间隔时间内允许的请求数） 时间间隔长度 时间间隔单位
        limiter.trySetRate(RateType.OVERALL,rate,interval,unit);
        // 打印日志
        log.debug("RateLimiter created with key: {}, rate: {}, interval: {}, unit: {}", key, rate, interval, unit);
        return  limiter;
    }


}
